package springboard.webapp.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Map;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping("/api/settings")
public class SettingsController {

    @ApiOperation("获取设置")
    @GetMapping("/props")
    @RequiresRoles("admin")
    public Properties loadProps(@ApiParam("设置文件路径") @RequestParam(value = "path", defaultValue = "springboard.properties") String path) {
        Properties prop = new Properties();
        try(InputStream in = new FileInputStream(path)) {
            prop.load(in);
        } catch(IOException x) {
            log.error("", x);
            prop.clear();
        }
        return prop;
    }

    @ApiOperation("保存设置")
    @PostMapping("/props")
    @RequiresRoles("admin")
    public Properties saveProps(@ApiParam("设置文件路径") @RequestParam(value = "path", defaultValue = "springboard.properties") String path,
                                @ApiParam("设置文件内容（字典格式）") @RequestBody Map<String, String> newProps) {
        Properties prop = new Properties();
        try(InputStream in = new FileInputStream(path)) {
            prop.load(in);
        } catch(IOException x) {
            throw new RuntimeException(x);
        }
        prop.putAll(newProps);
        try(OutputStream out = new FileOutputStream(path)) {
            prop.store(out, "");
        } catch(IOException x) {
            throw new RuntimeException(x);
        }
        return prop;
    }

}
